import React, { useState, useEffect } from "react";
import { List, Image, Button, Tabs, ErrorBlock, ImageViewer } from 'antd-mobile';
import EmptyBlock from "@/components/emptyBlock";
import { BankcardOutline } from 'antd-mobile-icons';
import { useNavigate } from 'react-router-dom';
import './index.css';
import orderApi from '@/api/iap/order.js';
import dayjs from "dayjs";

import zf_logo from '@/assets/logo/zf_logo.png'



const orderStatuses = [
    { name: '全部', value: '' },
    { name: '待支付', value: 0 },
    { name: '待发货', value: 10 },
    { name: '已发货', value: 20 },
    { name: '已完成', value: 30 },
    { name: '已取消', value: 40 },
];

// 根据订单状态返回对应的样式和图标
const getStatusConfig = (status) => {
    // 订单状态：UNPAID(0, "待支付"), UNDELIVERED(10, "待发货"), DELIVERED(20, "已发货"), COMPLETED(30, "已完成"), CANCELED(40, "已取消")
    switch (status) {
        // 待支付（强调行动点，用红色系）
        case 0:
            return {
                color: '#f53f3f', // 标准红色（强调需立即处理）
                bgColor: 'rgba(245, 63, 63, 0.1)', // 红色透明背景
                name: '待支付',
            };

        // 待发货（提醒状态，用橙色系）
        case 10:
            return {
                color: '#ff7d00', // 橙色（表示待处理的中间状态）
                bgColor: 'rgba(255, 125, 0, 0.1)',
                name: '待发货',
            };

        // 已发货（进行中状态，用蓝色系）
        case 20:
            return {
                color: '#1677ff', // 标准蓝色（表示流程进行中）
                bgColor: 'rgba(22, 119, 255, 0.1)',
                name: '已发货',
            };

        // 已完成（成功状态，用绿色系）
        case 30:
            return {
                color: '#00b42a', // 标准绿色（表示流程完成）
                bgColor: 'rgba(0, 180, 42, 0.1)',
                name: '已完成',
            };

        // 已取消（终止状态，用浅灰色系）
        case 40:
            return {
                color: '#86909c', // 浅灰色（表示已终止）
                bgColor: 'rgba(134, 144, 156, 0.1)',
                name: '已取消',
            };
        // 默认状态（兜底，用中性蓝色）
        default:
            return {
                color: '#409eff',
                bgColor: 'rgba(64, 158, 255, 0.1)',
                name: '未知状态',
            };
    }
};


export default function Order() {
    const navigate = useNavigate();
    const [orders, setOrders] = useState([]);
    const [orderStatus, setOrderStatus] = useState() // -1 全部
    const [imageData, setImageData] = useState({
        image: '',
        visible: false
    })

    const showNum = 1 //每个订单默认显示商品数量
    const itemHeight = 65 //每个商品数量占用高度 60 + 5
    const [orderExpandStatesMap, setOrderExpandStatesMap] = useState({})  //每个订单的状态（是否显示展开按钮、是否已展开）

    useEffect(() => {
        // 订单状态变化时重新获取订单数据
        getOrderList()
    }, [orderStatus])

    const getOrderList = async () => {
        let res = await orderApi.order_page({ pageNo: 1, pageSize: 10, status: orderStatus })
        let orders = res.data.list
        if (orders.length > 0) {
            const new_orderExpandStatesMap = {}
            orders.forEach((order) => {
                new_orderExpandStatesMap[order.id] = {
                    showBtn: order.items.length > showNum,
                    isOpen: false,
                }
            })
            setOrderExpandStatesMap(new_orderExpandStatesMap)
            setOrders(orders)
        }

    }
    // 返回我的页面
    const goBack = () => {
        navigate(-1);
    };


    // 取消订单
    const cancelOrder = (orderId, e) => {
        e.stopPropagation();
        // 纯前端演示，实际项目中可添加取消订单逻辑
        setOrders(orders.map(order =>
            order.id === orderId ? { ...order, status: 'cancelled', statusText: '已取消' } : order
        ));
    };

    // 支付订单
    const payOrder = async (order) => {
        console.log('payOrder', order)
        // 纯前端演示，实际项目中可添加支付逻辑
        let data = {
            id: order.payOrderId,
            channelCode: 'alipay_wap',
            displayMode: 'url',
            returnUrl: '',
        }
        let res = await orderApi.order_submit(data)
        console.log('提交支付订单', res)
        window.open(res.data.displayContent)
    };

    const openOrclose = (order) => {

        let new_orderExpandStatesMap = JSON.parse(JSON.stringify(orderExpandStatesMap))

        new_orderExpandStatesMap[order.id].isOpen = !new_orderExpandStatesMap[order.id].isOpen

        setOrderExpandStatesMap(new_orderExpandStatesMap)
    }


    return (
        <div className="order-page">
            {/* 顶部导航 */}
            <div className="order-header"> 我的订单 </div>

            <Tabs style={{ backgroundColor: '#fff' }} onChange={value => {
                setOrderStatus(value)
            }}>
                {orderStatuses.map(status => {
                    const { name, value } = status;
                    return <Tabs.Tab title={name} key={value} />;
                })}
            </Tabs>

            {/* 订单列表 */}
            {orders.length === 0 ? <EmptyBlock /> :
                <List className="order-list" style={{ '--adm-color-background': '#eee' }}>
                    {orders.map(order => {
                        const { color, bgColor, name } = getStatusConfig(order.status);
                        const isPending = order.status === 0;

                        return (
                            <div key={order.id} className="order-item">
                                {/* 订单头部 - 编号和状态 */}
                                <div className="order-header-info">
                                    <div className="order-name" style={{ backgroundColor: bgColor, color: color }} >{name}</div>
                                </div>

                                {/* 订单编号 */}
                                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '8px', padding: '0 5px' }}>
                                    <div className="order-id">订单编号: {order.orderNo}</div>
                                    <div className="order-time" >{dayjs(order.createTime).format('YYYY-MM-DD HH:mm:ss')}</div>
                                </div>

                                {/* 收货人 */}
                                <div className="address-card">
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                        <div style={{ fontSize: '14px' }}>{order.receiverName}</div>
                                        <div style={{ fontSize: '14px' }}>{order.receiverMobile}</div>
                                    </div>
                                    <div className="address-detail" style={{ fontSize: '12px', lineHeight: '16px', marginTop: '5px' }}>{order.receiverDetailAddress}</div>
                                </div>


                                {/* 商品列表 */}
                                <div className="product-list" style={{ height: orderExpandStatesMap[order.id].isOpen ? `${itemHeight * order.items.length}px` : `${itemHeight * showNum}px`, overflow: "hidden", transition: '0.3s' }}>
                                    {order.items.map(product => (
                                        <div key={product.id} className="product-item">
                                            <Image src={product.productPicAddr} onClick={() => { setImageData({ image: product.productPicAddr, visible: true }) }} alt={product.productName} className="product-image" />
                                            <div className="product-info">
                                                <div className="product-name">{product.productName}</div>
                                                <div className="product-price">¥{product.price.toFixed(2)}</div>
                                            </div>
                                            <div className="product-quantity">x {product.count}</div>
                                        </div>
                                    ))}
                                </div>

                                {/* 订单金额 */}
                                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', height: '30px' }}>
                                    {orderExpandStatesMap[order.id].showBtn && <Button color='primary' size="small" fill='none' onClick={() => { openOrclose(order) }} >{
                                        orderExpandStatesMap[order.id].isOpen ? '收起' : '展开'
                                    }</Button>}
                                    <b />
                                    <div className="order-amount" > 合计: <span className="total-price">¥{order.payPrice.toFixed(2)}</span> </div>
                                </div>
                                {/* 操作按钮 */}
                                {isPending && (
                                    <div className="order-actions">
                                        <div style={{ display: 'flex', alignItems: 'center' }}>
                                            <div style={{ fontSize: '14px' }}>支付方式：</div>
                                            <div style={{ display: 'flex', alignItems: 'center', border: '1px solid #409eff', padding: '4px 10px', borderRadius: '5px' }}>
                                                <Image style={{ width: '20px', height: '20px', marginRight: '10px' }} src={zf_logo}></Image>
                                                <span style={{ fontSize: '14px' }}>
                                                    支付宝
                                                </span>
                                            </div>
                                        </div>
                                        <Button className="action-btn pay-btn" onClick={(e) => payOrder(order)}> 立即支付 </Button>
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </List>
            }
            <ImageViewer image={imageData.image} visible={imageData.visible} onClose={() => { setImageData({ image: '', visible: false }) }} />

        </div>
    );
}
